<html lang="zh">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">
        <meta name="description" content="胃肠道症状评定量表(GSRS)自助评估工具，帮助用户评估胃肠道症状的严重程度，包括反流、腹泻、便秘、消化不良和恶心呕吐等症状，为健康管理提供参考。">
        <meta name="keywords" content="胃肠道症状评定量表, GSRS量表, 胃肠道健康评估, 消化系统症状, 反流症状, 腹泻, 便秘, 消化不良, 恶心呕吐">
        <meta name="custom-image" content="https://totemlife.cn/apps/public/gsrs-scale-cover.jpg">
        <title>胃肠道症状评定量表(GSRS)</title>
        <script src="/apps/js/baidu-tongji-mtx.js"></script>
        <link href="/apps/css/bootstrap.min.css" rel="stylesheet">
        <link href="/apps/css/fontawesome-free-6.4.0-web/css/all.css" rel="stylesheet">
        <style>
            /* 自定义颜色类 */
            .bg-teal {
                background-color: #20c997;
            }

            /* 页面样式 */
            body {
                background-color: #f8f9fa;
                padding-bottom: 60px;
            }

            footer {
                position: fixed;
                bottom: 0;
                width: 100%;
                background-color: rgba(15, 76, 129, 0.8);
                color: white;
                padding: 10px 15px;
                display: flex;
                justify-content: center;
                align-items: center;
                z-index: 1000;
            }

            /* 移动端优化 */
            @media (max-width: 576px) {
                /* 标题优化 */
                h1 {
                    font-size: 1.75rem;
                }

                h5 {
                    font-size: 1.1rem;
                }

                /* 表格响应式优化 */
                .table-responsive {
                    font-size: 0.875rem;
                }

                /* 历史记录表格优化 */
                .history-table th,
                .history-table td {
                    padding: 0.5rem 0.25rem;
                }

                /* 操作按钮优化 */
                .action-btns .btn {
                    padding: 0.25rem 0.5rem;
                    font-size: 0.75rem;
                }

                /* 评分按钮组优化 */
                .btn-group {
                    flex-wrap: wrap;
                }

                .btn-group .btn {
                    flex: 1 0 18%;
                    margin: 2px;
                    padding: 0.375rem 0.5rem;
                }

                /* 提交按钮优化 */
                .submit-btn {
                    height: 50px;
                    font-size: 1.1rem;
                }

                /* 问题卡片优化 */
                .question-card {
                    margin-bottom: 0.75rem;
                }

                .question-card .card-body {
                    padding: 0.75rem;
                }

                .question-card .card-title {
                    font-size: 1rem;
                }
            }

            /* 评分滑块样式 */
            .score-slider-container {
                padding: 10px 0;
            }

            .score-value {
                font-size: 32px;
                font-weight: bold;
                text-align: center;
                margin: 15px 0 5px;
                transition: all 0.3s;
            }

            .score-value.text-muted {
                font-size: 24px;
                opacity: 0.7;
            }

            .score-description {
                text-align: center;
                font-size: 16px;
                margin-bottom: 15px;
                color: #495057;
                transition: all 0.3s;
            }

            .score-slider {
                width: 100%;
                -webkit-appearance: none;
                height: 10px;
                border-radius: 5px;
                background: linear-gradient(to right, 
                    #28a745 0%, #28a745 16.66%, 
                    #17a2b8 16.66%, #17a2b8 33.33%, 
                    #ffc107 33.33%, #ffc107 50%, 
                    #ffc107 50%, #ffc107 66.66%, 
                    #fd7e14 66.66%, #fd7e14 83.33%, 
                    #dc3545 83.33%, #dc3545 100%);
                outline: none;
                transition: all 0.3s;
            }

            .score-slider::-webkit-slider-thumb {
                -webkit-appearance: none;
                appearance: none;
                width: 28px;
                height: 28px;
                border-radius: 50%;
                background: #fff;
                border: 2px solid #0d6efd;
                cursor: pointer;
                box-shadow: 0 0 5px rgba(0,0,0,0.2);
                transition: all 0.2s;
            }

            .score-slider::-moz-range-thumb {
                width: 28px;
                height: 28px;
                border-radius: 50%;
                background: #fff;
                border: 2px solid #0d6efd;
                cursor: pointer;
                box-shadow: 0 0 5px rgba(0,0,0,0.2);
                transition: all 0.2s;
            }

            .score-slider::-webkit-slider-thumb:active {
                transform: scale(1.2);
                box-shadow: 0 0 10px rgba(13,110,253,0.5);
            }

            .score-slider::-moz-range-thumb:active {
                transform: scale(1.2);
            }

            .score-labels {
                display: flex;
                justify-content: space-between;
                margin-top: 10px;
                font-size: 12px;
                color: #6c757d;
            }

            /* 分数颜色 */
            .score-value.score-0 { color: #28a745; }
            .score-value.score-1, .score-value.score-2 { color: #17a2b8; }
            .score-value.score-3, .score-value.score-4 { color: #ffc107; }
            .score-value.score-5 { color: #fd7e14; }
            .score-value.score-6 { color: #dc3545; }

            /* 垂直选项样式 */
            .score-options {
                display: flex;
                flex-direction: column;
                gap: 8px;
            }

            .score-option {
                display: flex;
                align-items: center;
                padding: 10px;
                border: 1px solid #dee2e6;
                border-radius: 5px;
                cursor: pointer;
                transition: all 0.2s;
            }

            .score-option.selected {
                background-color: #e7f1ff;
                border-color: #0d6efd;
            }

            .score-option-radio {
                margin-right: 10px;
            }

            .score-option-label {
                flex: 1;
            }

            .score-option-value {
                font-weight: bold;
                margin-right: 5px;
            }
        </style>
    </head>
    <body>
{{!-- GSRS胃肠道症状评定量表页面 --}}
<div class="container mt-4 mb-5">
    <div class="row">
        <div class="col-12">
            <div class="d-flex justify-content-between align-items-center mb-4">
                <h1>胃肠道症状评定量表(GSRS)</h1>
                <a href="/apps/scales/scales-dashboard" class="btn btn-outline-secondary">
                    <i class="fas fa-th-large"></i> 量表工具
                </a>
            </div>
            <div class="card shadow-sm mb-4">
                <div class="card-body">
                    <h5 class="card-title">关于GSRS量表</h5>
                    <p class="card-text">
                        胃肠道症状评定量表(Gastrointestinal Symptom Rating Scale, GSRS)是一种用于评估胃肠道症状严重程度的工具，通过评估反流症状、腹泻症状、便秘症状、消化不良症状和恶心呕吐等方面的表现，帮助用户了解自己的胃肠道健康状况。
                    </p>
                    <p class="card-text">
                        <strong>注意：</strong>本评估仅供参考，不能替代专业医疗机构的诊断。如有疑虑，请及时咨询专业医师。
                    </p>
                </div>
            </div>

            {{#if assessmentHistory.length}}
            <div class="card shadow-sm mb-4">
                <div class="card-header bg-light">
                    <h5 class="mb-0">历史评估记录</h5>
                </div>
                <div class="card-body p-0">
                    <div class="table-responsive">
                        <table class="table table-hover mb-0 history-table">
                            <thead>
                                <tr>
                                    <th>日期</th>
                                    <th>总分</th>
                                    <th>结果</th>
                                    <th>操作</th>
                                </tr>
                            </thead>
                            <tbody>
                                {{#each assessmentHistory}}
                                <tr>
                                    <td>{{formatDate assessment_date "YYYY-MM-DD HH:mm:ss"}}</td>
                                    <td>{{total_score}}</td>
                                    <td>
                                        <span class="badge {{#if (eq result_level '轻微')}}bg-success{{else if (eq result_level '中度')}}bg-warning{{else if (eq result_level '较重')}}bg-orange{{else}}bg-danger{{/if}}">
                                            {{result_level}}
                                        </span>
                                    </td>
                                    <td class="action-btns">
                                        <a href="/apps/scales/gsrs-scale/result/{{id}}" class="btn btn-sm btn-outline-primary">查看</a>
                                        <a href="/apps/scales/gsrs-scale/report/{{id}}" class="btn btn-sm btn-outline-secondary">报告</a>
                                    </td>
                                </tr>
                                {{/each}}
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
            {{/if}}

            <div class="card shadow-sm">
                <div class="card-body">
                    <h5 class="card-title">开始新评估</h5>
                    <p class="card-text">请点击下方按钮开始评估您的胃肠道症状。</p>

                    <div class="mt-3">
                        <button id="startAssessmentBtn" class="btn btn-primary w-100 submit-btn">开始评估</button>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

{{!-- 评估问卷模态框 --}}
<div class="modal fade" id="assessmentModal" tabindex="-1" aria-labelledby="assessmentModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-lg modal-dialog-scrollable modal-fullscreen-sm-down">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="assessmentModalLabel">GSRS胃肠道症状评估</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <div id="assessmentProgress" class="progress mb-3" style="height: 10px;">
                    <div class="progress-bar bg-info" role="progressbar" style="width: 0%;" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100"></div>
                </div>

                <form id="assessmentForm">
                    <div id="questionsContainer">
                        {{!-- 问题将通过JavaScript动态加载 --}}
                        <div class="text-center py-5">
                            <div class="spinner-border text-primary" role="status">
                                <span class="visually-hidden">加载中...</span>
                            </div>
                            <p class="mt-2">正在加载问题...</p>
                        </div>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                <button type="button" class="btn btn-primary" id="prevCategoryBtn" style="display: none;">上一类</button>
                <button type="button" class="btn btn-primary" id="nextCategoryBtn">下一类</button>
                <button type="button" class="btn btn-success" id="submitAssessmentBtn" style="display: none;">提交评估</button>
            </div>
        </div>
    </div>
</div>

{{!-- 结果模态框 --}}
<div class="modal fade" id="resultModal" tabindex="-1" aria-labelledby="resultModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered modal-fullscreen-sm-down">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="resultModalLabel">评估结果</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <div class="text-center mb-3">
                    <div id="resultIcon" class="mb-3">
                        <i class="fas fa-check-circle text-success fa-4x"></i>
                    </div>
                    <h4 id="resultTitle">评估完成</h4>
                    <p id="resultScore" class="fs-5">总分: <span>0</span></p>
                    <p id="resultAvgScore" class="fs-5">平均分: <span>0</span></p>
                    <p id="resultLevel" class="fs-5">结果: <span>轻微</span></p>
                    <p id="resultDescription" class="mt-3">您的胃肠道症状轻微，属于正常范围内的波动。</p>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">关闭</button>
                <a href="#" id="viewResultBtn" class="btn btn-primary">查看详细结果</a>
            </div>
        </div>
    </div>
</div>

{{!-- 自定义确认框 --}}
<div class="modal fade" id="customConfirmModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered modal-sm">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">提示</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <p id="customConfirmMessage"></p>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                <button type="button" class="btn btn-primary" id="customConfirmYesBtn">确定</button>
            </div>
        </div>
    </div>
</div>

{{!-- 警告模态框 --}}
<div class="modal fade" id="warningModal" tabindex="-1" aria-labelledby="warningModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="warningModalLabel">提示</h5>
            </div>
            <div class="modal-body">
                <p id="warningMessage"></p>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-primary" data-bs-dismiss="modal">继续作答</button>
            </div>
        </div>
    </div>
</div>

<!-- Footer -->
<footer>
    <div class="text-center">
        <a id="tmall-app-home-link" href="weixin://dl/business/?appid=wx1b441d1a37b278e1&path=pages/index/index&env_version=release" class="text-decoration-none">
            <span id="tmall-app-home-title" style="color: white; font-size: 16px; margin-left: 5px;">
                <i class="fa fa-house"></i> 广州图腾生命医学研究有限公司
            <span>
        </a>
        &copy; {{currentYear}}
    </div>
</footer>

<!-- 将所有JS文件移到这里，并添加defer属性 -->
<script src="https://res.wx.qq.com/open/js/jweixin-1.6.0.js" defer></script>
<script src="/apps/js/bootstrap.bundle.min.js" defer></script>
<script src="/apps/js/wx-client-dom.js" defer></script>
<script src="/apps/js/chart.js" defer></script>

<script>
    document.addEventListener('DOMContentLoaded', function() {
        // 全局变量
        let categories = [];
        let questions = {};
        let currentCategory = 0;
        let answers = {};

        // 获取DOM元素
        const startAssessmentBtn = document.getElementById('startAssessmentBtn');
        const assessmentModal = new bootstrap.Modal(document.getElementById('assessmentModal'));
        const resultModal = new bootstrap.Modal(document.getElementById('resultModal'));
        const warningModal = new bootstrap.Modal(document.getElementById('warningModal'));
        const warningMessage = document.getElementById('warningMessage');
        const questionsContainer = document.getElementById('questionsContainer');
        const prevCategoryBtn = document.getElementById('prevCategoryBtn');
        const nextCategoryBtn = document.getElementById('nextCategoryBtn');
        const submitAssessmentBtn = document.getElementById('submitAssessmentBtn');
        const progressBar = document.querySelector('#assessmentProgress .progress-bar');

        // 自定义确认框
        const customConfirmModal = new bootstrap.Modal(document.getElementById('customConfirmModal'));
        const customConfirmMessage = document.getElementById('customConfirmMessage');
        const customConfirmYesBtn = document.getElementById('customConfirmYesBtn');

        // 显示警告信息的函数
        function showWarning(message) {
            warningMessage.textContent = message;
            warningModal.show();
        }

        // 自定义确认框函数
        function showCustomConfirm(message, callback) {
            customConfirmMessage.textContent = message;
            customConfirmYesBtn.onclick = function() {
                customConfirmModal.hide();
                callback(true);
            };
            customConfirmModal.show();

            // 当模态框隐藏时，如果是通过关闭按钮或取消按钮，则返回 false
            const modalElement = document.getElementById('customConfirmModal');
            const onHidden = function() {
                if (customConfirmYesBtn.onclick) {
                    callback(false);
                    customConfirmYesBtn.onclick = null;
                }
                modalElement.removeEventListener('hidden.bs.modal', onHidden);
            };
            modalElement.addEventListener('hidden.bs.modal', onHidden);
        }

        // 开始评估按钮点击事件
        startAssessmentBtn.addEventListener('click', function() {
            // 加载问题并显示评估模态框
            loadQuestions();
            assessmentModal.show();
        });

        // 加载问题
        async function loadQuestions() {
            try {
                const response = await fetch('/apps/scales/gsrs-scale/questions');
                const data = await response.json();

                if (data.success) {
                    categories = data.categories;
                    questions = data.questions;

                    // 显示第一类问题
                    showCategory(1);
                } else {
                    alert('加载问题失败: ' + data.message);
                }
            } catch (error) {
                console.error('加载问题错误:', error);
                alert('加载问题失败，请稍后重试');
            }
        }

        // 显示指定类别的问题
        function showCategory(categoryId) {
            currentCategory = categoryId;

            // 更新进度条
            const progress = (categoryId - 1) / categories.length * 100;
            progressBar.style.width = progress + '%';
            progressBar.setAttribute('aria-valuenow', progress);

            // 获取当前类别的问题
            const categoryQuestions = questions[categoryId] || [];
            const category = categories.find(c => c.id === categoryId) || { name: '未知类别' };

            // 构建问题HTML
            let html = `
                <div class="mb-4">
                    <h4 class="mb-3">第${categoryId}部分: ${category.name}</h4>
                    <p class="text-muted mb-4">请根据您在过去一周内的症状，选择最符合的选项。</p>
                </div>
            `;

            categoryQuestions.forEach(question => {
                const questionId = question.id;
                const selectedValue = answers[questionId] || '';

                html += `
                    <div class="card mb-3">
                        <div class="card-body">
                            <h5 class="card-title">${question.question_text}</h5>
                            <div class="mt-3">
                                <!-- 桌面端按钮组 -->
                                <div class="btn-group w-100 d-none d-md-flex" role="group">
                                    <input type="radio" class="btn-check" name="question_${questionId}" id="q${questionId}_0" value="0" ${selectedValue === '0' ? 'checked' : ''}>
                                    <label class="btn btn-outline-primary" for="q${questionId}_0">0 完全没有</label>

                                    <input type="radio" class="btn-check" name="question_${questionId}" id="q${questionId}_1" value="1" ${selectedValue === '1' ? 'checked' : ''}>
                                    <label class="btn btn-outline-primary" for="q${questionId}_1">1 稍微有</label>

                                    <input type="radio" class="btn-check" name="question_${questionId}" id="q${questionId}_2" value="2" ${selectedValue === '2' ? 'checked' : ''}>
                                    <label class="btn btn-outline-primary" for="q${questionId}_2">2 少量有</label>

                                    <input type="radio" class="btn-check" name="question_${questionId}" id="q${questionId}_3" value="3" ${selectedValue === '3' ? 'checked' : ''}>
                                    <label class="btn btn-outline-primary" for="q${questionId}_3">3 中等程度</label>

                                    <input type="radio" class="btn-check" name="question_${questionId}" id="q${questionId}_4" value="4" ${selectedValue === '4' ? 'checked' : ''}>
                                    <label class="btn btn-outline-primary" for="q${questionId}_4">4 较明显不适</label>

                                    <input type="radio" class="btn-check" name="question_${questionId}" id="q${questionId}_5" value="5" ${selectedValue === '5' ? 'checked' : ''}>
                                    <label class="btn btn-outline-primary" for="q${questionId}_5">5 比较严重</label>

                                    <input type="radio" class="btn-check" name="question_${questionId}" id="q${questionId}_6" value="6" ${selectedValue === '6' ? 'checked' : ''}>
                                    <label class="btn btn-outline-primary" for="q${questionId}_6">6 特别严重</label>
                                </div>

                                <!-- 移动端滑块 -->
                                <div class="d-md-none">
                                    <div class="score-slider-container">
                                        <div class="score-value ${selectedValue === '' ? 'text-muted' : 'score-' + selectedValue}" id="score_value_${questionId}">
                                            ${selectedValue === '' ? '未选择' : selectedValue}
                                        </div>
                                        <div class="score-description" id="score_desc_${questionId}">
                                            ${selectedValue === '' ? '请选择严重程度' : getScoreDescription(selectedValue)}
                                        </div>
                                        <input type="range" class="score-slider" id="slider_${questionId}" 
                                               min="0" max="6" step="1" value="${selectedValue !== '' ? selectedValue : '0'}"
                                               style="opacity: ${selectedValue === '' ? '0.5' : '1'}">
                                        <div class="score-labels">
                                            <span>0</span>
                                            <span>1</span>
                                            <span>2</span>
                                            <span>3</span>
                                            <span>4</span>
                                            <span>5</span>
                                            <span>6</span>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                `;
            });

            questionsContainer.innerHTML = html;

            // 更新按钮状态
            prevCategoryBtn.style.display = categoryId > 1 ? 'block' : 'none';

            if (categoryId < categories.length) {
                nextCategoryBtn.style.display = 'block';
                submitAssessmentBtn.style.display = 'none';
                nextCategoryBtn.textContent = '下一类';
            } else {
                nextCategoryBtn.style.display = 'none';
                submitAssessmentBtn.style.display = 'block';
            }

            // 添加问题选项的事件监听
            categoryQuestions.forEach(question => {
                const questionId = question.id;

                // 桌面端单选按钮事件监听
                const options = document.querySelectorAll(`input[name="question_${questionId}"]`);
                options.forEach(option => {
                    option.addEventListener('change', function() {
                        answers[questionId] = this.value;
                    });
                });

                // 移动端滑块事件监听
                const slider = document.getElementById(`slider_${questionId}`);
                if (slider) {
                    slider.addEventListener('input', function() {
                        const value = this.value;
                        answers[questionId] = value;

                        // 更新显示的值和描述
                        const valueDisplay = document.getElementById(`score_value_${questionId}`);
                        const descDisplay = document.getElementById(`score_desc_${questionId}`);

                        if (valueDisplay) {
                            valueDisplay.textContent = value;
                            // 更新样式
                            valueDisplay.className = 'score-value score-' + value;
                        }
                        if (descDisplay) {
                            descDisplay.textContent = getScoreDescription(value);
                        }

                        // 更新滑块透明度
                        this.style.opacity = '1';

                        // 同步桌面端单选按钮
                        const radioBtn = document.getElementById(`q${questionId}_${value}`);
                        if (radioBtn) radioBtn.checked = true;
                    });
                }
            });
        }

        // 获取分数对应的描述
        function getScoreDescription(value) {
            const descriptions = [
                '完全没有',
                '稍微有',
                '少量有',
                '中等程度',
                '较明显不适',
                '比较严重',
                '特别严重'
            ];

            return descriptions[parseInt(value)] || '';
        }

        // 上一类按钮点击事件
        prevCategoryBtn.addEventListener('click', function() {
            if (currentCategory > 1) {
                showCategory(currentCategory - 1);
            }
        });

        // 下一类按钮点击事件
        nextCategoryBtn.addEventListener('click', function() {
            // 检查当前类别的问题是否都已回答
            const categoryQuestions = questions[currentCategory] || [];
            let unansweredQuestions = [];

            categoryQuestions.forEach(question => {
                if (!answers[question.id]) {
                    unansweredQuestions.push(question.id);
                }
            });

            if (unansweredQuestions.length > 0) {
                // 高亮显示未回答的问题
                unansweredQuestions.forEach(questionId => {
                    const questionCard = document.querySelector(`#question_${questionId}`);
                    if (questionCard) {
                        questionCard.classList.add('border-danger');
                        // 3秒后移除高亮
                        setTimeout(() => {
                            questionCard.classList.remove('border-danger');
                        }, 3000);
                    }
                });
                showWarning('请回答所有问题后再继续');
                return;
            }

            if (currentCategory < categories.length) {
                showCategory(currentCategory + 1);
            }
        });

        // 提交评估按钮点击事件
        submitAssessmentBtn.addEventListener('click', async function() {
            // 检查是否所有问题都已回答
            let unansweredQuestions = [];

            for (const categoryId in questions) {
                questions[categoryId].forEach(question => {
                    if (!answers[question.id]) {
                        unansweredQuestions.push(question.id);
                    }
                });
            }

            if (unansweredQuestions.length > 0) {
                // 切换到包含第一个未回答问题的类别
                const firstUnansweredId = unansweredQuestions[0];
                let targetCategory = 1;

                // 查找包含未回答问题的类别
                for (const categoryId in questions) {
                    if (questions[categoryId].some(q => q.id === firstUnansweredId)) {
                        targetCategory = parseInt(categoryId);
                        break;
                    }
                }

                showCategory(targetCategory);

                // 高亮显示未回答的问题
                unansweredQuestions.forEach(questionId => {
                    const questionCard = document.querySelector(`#question_${questionId}`);
                    if (questionCard) {
                        questionCard.classList.add('border-danger');
                        // 3秒后移除高亮
                        setTimeout(() => {
                            questionCard.classList.remove('border-danger');
                        }, 3000);
                    }
                });

                showWarning(`还有 ${unansweredQuestions.length} 个问题未回答，请完成所有问题后再提交`);
                return;
            }

            await submitAssessment();
        });

        // 提交评估函数
        async function submitAssessment() {
            try {
                // 提交评估
                const response = await fetch('/apps/scales/gsrs-scale/submit', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({
                        answers: answers
                    })
                });

                const data = await response.json();

                if (data.success) {
                    // 关闭评估模态框
                    assessmentModal.hide();

                    // 更新结果模态框内容
                    document.querySelector('#resultScore span').textContent = data.totalScore;
                    document.querySelector('#resultAvgScore span').textContent = data.avgScore;
                    document.querySelector('#resultLevel span').textContent = data.resultLevel;
                    document.getElementById('resultDescription').textContent = data.resultDescription;

                    // 设置结果图标和颜色
                    const resultIcon = document.getElementById('resultIcon');
                    if (data.resultLevel === '轻微') {
                        resultIcon.innerHTML = '<i class="fas fa-check-circle text-success fa-4x"></i>';
                    } else if (data.resultLevel === '中度') {
                        resultIcon.innerHTML = '<i class="fas fa-exclamation-circle text-warning fa-4x"></i>';
                    } else if (data.resultLevel === '较重') {
                        resultIcon.innerHTML = '<i class="fas fa-exclamation-triangle text-orange fa-4x"></i>';
                    } else {
                        resultIcon.innerHTML = '<i class="fas fa-times-circle text-danger fa-4x"></i>';
                    }

                    // 设置查看详细结果按钮链接
                    document.getElementById('viewResultBtn').href = `/apps/scales/gsrs-scale/result/${data.assessmentId}`;

                    // 显示结果模态框
                    resultModal.show();

                    // 重置答案
                    answers = {};
                } else {
                    alert('提交评估失败: ' + data.message);
                }
            } catch (error) {
                console.error('提交评估错误:', error);
                alert('提交评估失败，请稍后重试');
            }
        }
    });
</script>

</body>
</html> 
